package com.gufe.system.common;

import com.gufe.common.core.domain.entity.ApiResponse;
import com.gufe.common.core.domain.entity.BaseSystemUser;
import com.gufe.common.utils.sign.Md5Utils;
import com.gufe.system.domain.BaseSystemOrg;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;



@Service
@Slf4j
public class BaseSystemService {
    private final RestTemplate restTemplate;
    private final OpenApiProperties openApiProperties;

    public BaseSystemService(RestTemplate restTemplate, OpenApiProperties openApiProperties) {
        this.restTemplate = restTemplate;
        this.openApiProperties = openApiProperties;
    }


    // ----------------------- 公共方法：生成签名 ------------------------
    private String generateSign(Long timestamp) {
        String raw = timestamp + openApiProperties.getAppSecret();
        return Md5Utils.hash(raw);
    }

    private Long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }

    // ----------------------- 接口调用方法 ------------------------

    /**
     * 调用远程 /getUserInfo 接口
     *
     * @param code 授权码
     * @return 用户信息，失败返回 null 或抛异常
     */
    public ApiResponse<BaseSystemUser> getUserInfo(String code) {
        Long timestamp = getCurrentTimestamp();
        String sign = generateSign(timestamp);
        String url = openApiProperties.getBaseUrl() + "/getUserInfo";

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("appId", openApiProperties.getAppId())
                .queryParam("code", code)
                .queryParam("timestamp", timestamp)
                .queryParam("sign", sign);

        // ✅ 使用 exchange + ParameterizedTypeReference
        RequestEntity<Void> request = RequestEntity.get(builder.build().toUri())
                .accept(MediaType.APPLICATION_JSON)
                .build();

        try {
            ResponseEntity<ApiResponse<BaseSystemUser>> response = restTemplate.exchange(
                    request,
                    new ParameterizedTypeReference<ApiResponse<BaseSystemUser>>() {}
            );

            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                log.warn("调用 getUserInfo 失败，HTTP状态码: {}", response.getStatusCode());
                return buildFailResponse("HTTP调用失败");
            }

        } catch (Exception e) {
            log.error("调用 getUserInfo 异常", e);
            return buildFailResponse("网络异常: " + e.getMessage());
        }
    }

    private <T> ApiResponse<T> buildFailResponse(String msg) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(500);
        response.setMsg(msg);
        return response;
    }
    /**
     * 调用远程 /getSystemOrg 接口
     *
     * @return 完整组织结构数据
     */
    public ApiResponse<BaseSystemOrg> getSystemOrg() {
        Long timestamp = getCurrentTimestamp();
        String sign = generateSign(timestamp);
        String url = openApiProperties.getBaseUrl() + "/getSystemOrg";

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("appId", openApiProperties.getAppId())
                .queryParam("timestamp", timestamp)
                .queryParam("sign", sign);

        RequestEntity<Void> request = RequestEntity.get(builder.build().toUri())
                .accept(MediaType.APPLICATION_JSON)
                .build();

        try {
            ResponseEntity<ApiResponse<BaseSystemOrg>> response = restTemplate.exchange(
                    request,
                    new ParameterizedTypeReference<ApiResponse<BaseSystemOrg>>() {}
            );

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return response.getBody();
            } else {
                log.warn("调用 getSystemOrg 失败，HTTP状态码: {}", response.getStatusCode());
                return buildFailResponse("HTTP调用失败");
            }

        } catch (Exception e) {
            log.error("调用 getSystemOrg 异常", e);
            return buildFailResponse("网络异常: " + e.getMessage());
        }
    }

    // ----------------------- 便捷方法（可选）------------------------

    /**
     * 获取用户信息，只返回业务数据（忽略封装）
     */
    public BaseSystemUser getUserInfoData(String code) {
        ApiResponse<BaseSystemUser> resp = getUserInfo(code);
        return resp.isSuccess() ? resp.getData() : null;
    }

    /**
     * 获取组织结构数据（忽略封装）
     */
    public BaseSystemOrg getSystemOrgData() {
        ApiResponse<BaseSystemOrg> resp = getSystemOrg();
        return resp.isSuccess() ? resp.getData() : null;
    }
}
